#!/usr/bin/python3.6
import logging
import time
import urllib3
import requests
import json
import os



def getBranches(value):
    branchs=[]
    r = http.request('GET', value['_links']['repo_branches'],headers=headers)
    # 获得html源码,utf-8解码
    json_response = (r.data.decode())
    # print(json_response)

    dict_json = json.loads(json_response)
    #
    # print(dict_json)
    for value in dict_json:
        branchs.append(value['name'])

    # print(branchs)
    return branchs

logger = logging.getLogger("gitlab")
logger.setLevel(logging.DEBUG)
# 建立一个streamhandler来把日志打在CMD窗口上，级别为error以上
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# 设置日志格式
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
#将相应的handler添加在logger对象中
logger.addHandler(ch)


tarGzTemp="/tmp/win"
pathTemp="/media/worktemplinux/gitlab_bak"

#  忽略警告：InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised.
requests.packages.urllib3.disable_warnings()
# 一个PoolManager实例来生成请求, 由该实例对象处理与线程池的连接以及线程安全的所有细节
http = urllib3.PoolManager()
# 通过request()方法创建一个请求：

headers = {
'PRIVATE-TOKEN': 'W9QfD9YL-UrFGRu5vnqN'
}



r = http.request('GET', 'http://192.168.0.199/api/v4/projects?per_page=500',headers=headers)
print(r.status) # 200

# 获得html源码,utf-8解码
json_response = (r.data.decode())

print(json_response)
#
dict_json = json.loads(json_response)
#
print(dict_json)

for value in dict_json:
    logger.debug(value)
    # 要备份的分支
    branch={"master","release"}
    branchsTemp=getBranches(value)
    logger.debug("branchsTemp=%s" %(branchsTemp))
    for temp in branchsTemp:
        if temp not in branch:
            continue
        savePath=pathTemp+"/"+value['path_with_namespace']+"/"+temp
        exists = os.path.exists(savePath)
        logger.debug("%s=%s", exists,savePath)
        if not exists:
            os.makedirs(savePath)

        if os.path.exists(savePath + "/.git"):
            execStr=("git -C %s pull %s" %(savePath,value['http_url_to_repo']))
            logger.debug (execStr)
            # os.system(execStr)  只显示脚本的退出状态码
            os.popen(execStr)
        else:
            execStr="git clone -b %s %s %s" %(temp,value['http_url_to_repo'],savePath)
            logger.debug (execStr)
            os.popen(execStr)
execStr="tar -zcvf %s/%s.tar.gz --exclude=*.svn --exclude=*.git --exclude=*.repo %s" %(tarGzTemp,time.strftime("%Yy%mm%dd%H%M%S", time.localtime()),pathTemp)
logger.debug(execStr)
os.popen(execStr)

